package com.jsh.erp.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jsh.erp.constants.ExceptionConstants;

import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.JshUserChangeMapper;
import com.jsh.erp.datasource.mappers.UserBusinessMapper;
import com.jsh.erp.datasource.vo.TreeNodeEx;
import com.jsh.erp.exception.BusinessParamCheckingException;
import com.jsh.erp.service.ISysDepartService;
import com.jsh.erp.service.ISysDictService;
import com.jsh.erp.service.ISysUserService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.service.role.RoleService;
import com.jsh.erp.service.tenant.TenantService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.*;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;

import com.jsh.common.api.response.CommonCode;
import com.jsh.common.api.response.QueryResponseResult;
import com.jsh.common.api.vo.Result;
import com.jsh.common.constant.CommonConstant;
import com.jsh.common.system.api.ISysBaseAPI;
import com.jsh.common.system.vo.LoginUser;
import com.jsh.common.util.PasswordUtil;
import com.jsh.common.util.RedisUtil;
import com.jsh.common.util.oConvertUtils;
import com.jsh.config.exception.ExceptionCast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;

/**
 * @author ji_sheng_hua 华夏erp
 */
@Slf4j
@RestController
@RequestMapping(value = "/user")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${manage.roleId}")
    private Integer manageRoleId;

    @Value("${demonstrate.open}")
    private boolean demonstrateOpen;
    @Autowired
    private UserService userService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ISysDictService sysDictService;
    @Resource
    private TenantService tenantService;
    @Resource
    private RedisService redisService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysBaseAPI iSysBaseAPI;
    @Autowired
    private JshUserChangeMapper jshUserChangeMapper;
    @Resource
    private LogService logService;
    @Resource
    private RoleService roleService;
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    UserBusinessMapper userBusinessMapper;//特殊情况

    private static final String TEST_USER = "jsh";
    private static String SUCCESS = "操作成功";
    private static String ERROR = "操作失败";
    private static final String HTTP = "http://";
    private static final String CODE_OK = "200";
    private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";

    @Value("${URL.LoginUrl}")
    String loginUrl;
    @Value("${URL.getLoginUserUrl}")
    String getLoginUserUrl;
    @Value("${clientId}")
    private String clientId;

    @Value("${redirectUrl}")
    private String redirectUrl;

    @Value("${response_type}")
    private String response_type;

    @Value("${clientSecret}")
    private String clientSecret;

    @Value("${URL.getRoleList}")
    String getRoleList;

    @Value("${URL.getUserRole}")
    String getUserRole;


    @SneakyThrows
    @PostMapping(value = "/login")
    public QueryResponseResult login(@RequestBody SysLoginModel sysLoginModel) {

        QueryResponseResult queryResponseResult = restTemplate.postForObject(loginUrl, sysLoginModel, QueryResponseResult.class);//远程调用oauth2 执行登陆

        HashMap<Object, Object> map = new HashMap<>();
        if (!queryResponseResult.isSuccess()) {
            ExceptionCast.cast(false, 9999, "第三方登录失败");
        }
        String token = (String) queryResponseResult.getObject();//获取oauth2 token

        SysUser sysUser = tokenGetSysUser(token);


        redisService.storageObjectBySession(token, "userId", sysUser.getId());


        if (sysUser.getTenantId() != null) {
            redisService.storageObjectBySession(token, "tenantId", sysUser.getTenantId()); //租户tenantId
            redisService.storageObjectBySession(token, "userNumLimit", 10000); //用户限制数
            redisService.storageObjectBySession(token, "billsNumLimit", 10000); //单据限制数
        }

        String roleType = "";

        roleType = userService.getRoleTypeByUserId(sysUser.getId()); //角色类型
        if (roleType == null) {
            roleType = "个人数据";
        }
        redisService.storageObjectBySession(token, "roleType", roleType);
        redisService.storageObjectBySession(token, "token", token);


        JSONArray btnStrArr = userService.getBtnStrArrById(Long.parseLong(sysUser.getId()));
        map.put("token", token);
        map.put("user", sysUser);
        //用户的按钮权限
        if (!"admin".equals(sysUser.getUsername())) {
            map.put("userBtn", btnStrArr);
        } else {
            map.put("userBtn", btnStrArr);
        }
        map.put("roleType", roleType);




        //更新当前用户角色

        String LoginUserUrl = getUserRole + "/" + map.get("token") + "?clientId=" + clientId + "&clientSecret=" + clientSecret;
        QueryResponseResult sysUserResult = restTemplate.getForObject(LoginUserUrl, QueryResponseResult.class);
        if (!sysUserResult.isSuccess()) {
            ExceptionCast.cast(false, 9999, "更新当前用户角色失败");
        }
        HashMap hashMap = (HashMap) sysUserResult.getObject();
        hashMap.remove("createTime");
        hashMap.remove("updateTime");
        SysRole sysRole = new SysRole();
        BeanUtils.populate(sysRole, hashMap);
        String roleName = sysRole.getRoleName();
        if (roleName.equals("超级管理员")) {
            roleName = "admin";
        }
        Role role = roleService.getRoleByName(roleName);

        String id = sysUser.getId();

        UserBusiness userBusiness = userBusinessMapper.selectOne(new LambdaQueryWrapper<UserBusiness>()
                .eq(UserBusiness::getKeyId, id)
                .eq(UserBusiness::getType, "UserRole"));

        if (userBusiness == null) {
            UserBusiness userBusiness1 = new UserBusiness();
            userBusiness1.setType("UserRole");
            userBusiness1.setKeyId(id);
            userBusiness1.setValue("[" + role.getId() + "]");
            userBusiness1.setDeleteFlag("0");
            userBusinessMapper.insert(userBusiness1);
        } else {
            userBusiness.setValue("[" + role.getId() + "]");
            String value = userBusiness.getValue().substring(1, userBusiness.getValue().length() - 1);
            String roleId = role.getId().toString();
            if (!value.equals(roleId)) {
                userBusinessMapper.updateById(userBusiness);
            }
        }

        return new QueryResponseResult(CommonCode.SUCCESS, map);
    }


    /**
     * create by: JiangYaoFeng
     * description: 调用第三方获取用户信息
     */

    @PostMapping(value = "/GetSysUser")
    @SneakyThrows
    QueryResponseResult GetSysUser(String token) {
        SysUser sysUser = tokenGetSysUser(token);

        return new QueryResponseResult(CommonCode.SUCCESS, sysUser);
    }

    @SneakyThrows
    SysUser tokenGetSysUser(String token) {

        String LoginUserUrl = getLoginUserUrl + "/" + token + "?clientId=" + clientId + "&clientSecret=" + clientSecret;
        //调用第三方获取用户信息
        QueryResponseResult sysUserResult = restTemplate.getForObject(LoginUserUrl, QueryResponseResult.class);

        if (!sysUserResult.isSuccess()) {
            ExceptionCast.cast(false, 9999, sysUserResult.getMessage());
        }


        HashMap hashMap = (HashMap) sysUserResult.getObject();
        SysUser sysUser = new SysUser();
//            BeanUtils.populate(sysUser,hashMap);

        Class<? extends SysUser> aClass = sysUser.getClass();
        BeanInfo beanInfo = Introspector.getBeanInfo(aClass);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor prop : propertyDescriptors) {
            String key = prop.getName();
            Class<? extends PropertyDescriptor> aClass1 = prop.getClass();
            if (hashMap.containsKey(key) && hashMap.get(key) != null) {
                Object value = hashMap.get(key);
                Method setMethod = prop.getWriteMethod();
                Class<?> propertyType = prop.getPropertyType();
                if (propertyType.equals(Date.class)) {
                    String[] pattern = new String[]{"yyyy-MM", "yyyyMM", "yyyy/MM", "yyyyMMdd", "yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMddHHmmss", "yyyyMMdd HHmmss", "yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss"};
                    Date date = DateUtils.parseDate(value.toString(), pattern);
                    setMethod.invoke(sysUser, date);
                } else {
                    setMethod.invoke(sysUser, value);
                }
            }
        }
        return sysUser;

    }


    /**
     * create by: JiangYaoFeng
     * description: 获取初始化数据 在免登录时调用
     */
    @SneakyThrows
    @GetMapping(value = "/getInitData")
    public QueryResponseResult login(HttpServletRequest request) {


        String token = request.getHeader(CommonConstant.ACCESS_TOKEN);
        SysUser sysUser = tokenGetSysUser(token);

        HashMap<Object, Object> map = new HashMap<>();
        boolean b = redisUtil.hasKey(token);
        if (!b) {
            redisService.storageObjectBySession(token, "userId", sysUser.getId());
        }


        if (sysUser.getTenantId() != null) {
            redisService.storageObjectBySession(token, "tenantId", sysUser.getTenantId()); //租户tenantId
            redisService.storageObjectBySession(token, "userNumLimit", 10000); //用户限制数
            redisService.storageObjectBySession(token, "billsNumLimit", 10000); //单据限制数
        }


        String roleType = "";
        roleType = userService.getRoleTypeByUserId(sysUser.getId()); //角色类型
        if (roleType == null) {
            roleType = "个人数据";
        }
        if (!b) {
            redisService.storageObjectBySession(token, "roleType", roleType);
            redisService.storageObjectBySession(token, "token", token);
        }
        JSONArray btnStrArr = userService.getBtnStrArrById(Long.parseLong(sysUser.getId()));
        map.put("token", token);
        map.put("user", sysUser);
        //用户的按钮权限
        if (!"admin".equals(sysUser.getUsername())) {
            map.put("userBtn", btnStrArr);
        } else {
            map.put("userBtn", btnStrArr);
        }
        map.put("roleType", roleType);


        //更新当前用户角色

        String LoginUserUrl = getUserRole + "/" + map.get("token") + "?clientId=" + clientId + "&clientSecret=" + clientSecret;
        QueryResponseResult sysUserResult = restTemplate.getForObject(LoginUserUrl, QueryResponseResult.class);
        if (!sysUserResult.isSuccess()) {
            ExceptionCast.cast(false, 9999, "更新当前用户角色失败");
        }
        SysRole sysRole = (SysRole) sysUserResult.getObject();
        String roleName = sysRole.getRoleName();
        if (roleName.equals("超级管理员")) {
            roleName = "admin";
        }
        Role role = roleService.getRoleByName(roleName);

        String id = sysUser.getId();

        UserBusiness userBusiness = userBusinessMapper.selectOne(new LambdaQueryWrapper<UserBusiness>()
                .eq(UserBusiness::getKeyId, id)
                .eq(UserBusiness::getType, "UserRole"));

        if (userBusiness == null) {
            UserBusiness userBusiness1 = new UserBusiness();
            userBusiness1.setType("UserRole");
            userBusiness1.setKeyId(id);
            userBusiness1.setValue("[" + role.getId() + "]");
            userBusiness1.setDeleteFlag("0");
            userBusinessMapper.insert(userBusiness1);
        } else {
            userBusiness.setValue("[" + role.getId() + "]");
            String value = userBusiness.getValue().substring(1, userBusiness.getValue().length() - 1);
            String roleId = role.getId().toString();
            if (!value.equals(roleId)) {
                userBusinessMapper.updateById(userBusiness);
            }
        }


        return new QueryResponseResult(CommonCode.SUCCESS, map);
    }


    /**
     * create by: JiangYaoFeng
     * description: jeecg 远程调用此接口 刷新角色数据
     */
    @SneakyThrows
    @GetMapping(value = "/pullTheUpdate")
    public boolean pullTheUpdate() {
        return allList();
    }

    @ApiOperation(value = "同步角色列表  以及租户信息")
    public boolean allList() throws Exception {


        //需要客户端   clentId  以及  clintSecret
        String url = getRoleList + "?clientId=" + clientId + "&clientSecret=" + clientSecret;


        QueryResponseResult forObject = restTemplate.getForObject(url, QueryResponseResult.class);
        if (!forObject.isSuccess()) {
            ExceptionCast.cast(false, 9999, forObject.getMessage());
        }

        List<HashMap> list = (List<HashMap>) forObject.getObject();

        ArrayList<SysRole> SysRoleList = new ArrayList<SysRole>();//jeect 角色
        for (HashMap hashMap : list) {
            hashMap.remove("createTime");
            hashMap.remove("updateTime");
            if (hashMap.get("roleName").equals("超级管理员")) {
                hashMap.put("roleName", "admin");
            }
            SysRole sysRole = new SysRole();
            BeanUtils.populate(sysRole, hashMap);
            SysRoleList.add(sysRole);
        }

        List<Role> roles = roleService.allList(); //erp角色

        List<String> erpNames = roles.stream().map(Role::getName).collect(Collectors.toList());//erp角色name
        List<String> jeecgNames = SysRoleList.stream().map(SysRole::getRoleName).collect(Collectors.toList());//jeect角色name


        List<SysRole> add = SysRoleList.stream().filter(s -> !erpNames.contains(s.getRoleName())).collect(Collectors.toList());//erp中没有 jeecg有的角色
        List<Long> del = roles.stream().filter(s -> !jeecgNames.contains(s.getName())).map(Role::getId).collect(Collectors.toList());//jeecg中没有 erp有的角色


        int i = roleService.deleteRoleByIds(del);


        for (SysRole sysRole : add) {
            Role role = new Role();
            role.setDeleteFlag("0");
            role.setDescription(sysRole.getDescription());
            role.setName(sysRole.getRoleName());
            role.setType(sysRole.getType());
            roleService.addRole(role);
        }


        return forObject.isSuccess();
    }


    /**
     * 退出登录
     *
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "/logout")
    public Result<Object> logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //支持多地登陆 不删除token  客户端删除本地


//        //用户退出逻辑
//        String token = request.getHeader(CommonConstant.ERP_X_ACCESS_TOKEN);
//        if (oConvertUtils.isEmpty(token)) {
//            return Result.error("退出登录失败！");
//        }
//        String username = JwtUtil.getUsername(token);
//        LoginUser sysUser = iSysBaseAPI.getUserByName(username);
//        if (sysUser != null) {
//            redisService.deleteObjectBySession(request, "user");
//            redisService.deleteObjectBySession(request, "tenantId");
//            redisService.deleteObjectBySession(request, "userNumLimit");
//            redisService.deleteObjectBySession(request, "billsNumLimit");
//            log.info(" 用户名:  " + sysUser.getRealname() + ",退出成功！ ");
//            //清空用户登录Token缓存
//            redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
//            return Result.ok("退出登录成功！");
//        } else {
//            return Result.error("Token无效!");
//        }
        return null;
    }


    /**
     * 用户列表，用于用户下拉框
     *
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getUserList")
    public JSONArray getUserList(HttpServletRequest request) throws Exception {
        JSONArray dataArray = new JSONArray();
        try {
            List<User> dataList = userService.getUser();
            if (null != dataList) {
                for (User user : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("id", user.getId());
                    item.put("userName", user.getUsername());
                    dataArray.add(item);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataArray;
    }


    @GetMapping(value = "/getUserSession")
    public BaseResponseInfo getSessionUser(HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        try {
            Map<String, Object> data = new HashMap<>();
            Long userId = Long.parseLong(redisService.getObjectFromSessionByKey(request, "userId").toString());
            User user = userService.getUser(userId);
            user.setPassword(null);
            data.put("user", user);
            res.code = 200;
            res.data = data;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "获取session失败";
        }
        return res;
    }


    @PostMapping(value = "/resetPwd")
    public String resetPwd(@RequestBody JSONObject jsonObject,
                           HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        Long id = jsonObject.getLong("id");
        String password = "123456";
        String md5Pwd = Tools.md5Encryp(password);
        int update = userService.resetPwd(md5Pwd, id);
        if (update > 0) {
            return returnJson(objectMap, SUCCESS, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, ERROR, ErpInfo.ERROR.code);
        }
    }

    @PutMapping(value = "/updatePwd")
    public String updatePwd(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        Integer flag = 0;
        Map<String, Object> objectMap = new HashMap<String, Object>();
        try {
            String info = "";
            Long userId = jsonObject.getLong("userId");
            String oldpwd = jsonObject.getString("oldpassword");
            String password = jsonObject.getString("password");
            User user = userService.getUser(userId);
            String oldPassword = Tools.md5Encryp(oldpwd);
            String md5Pwd = Tools.md5Encryp(password);
            //必须和原始密码一致才可以更新密码
            if (demonstrateOpen && user.getLoginName().equals(TEST_USER)) {
                flag = 3; //jsh用户不能修改密码
                info = "jsh用户不能修改密码";
            } else if (oldPassword.equalsIgnoreCase(user.getPassword())) {
                user.setPassword(md5Pwd);
                flag = userService.updateUserByObj(user); //1-成功
                info = "修改成功";
            } else {
                flag = 2; //原始密码输入错误
                info = "原始密码输入错误";
            }
            objectMap.put("status", flag);
            if (flag > 0) {
                return returnJson(objectMap, info, ErpInfo.OK.code);
            } else {
                return returnJson(objectMap, ERROR, ErpInfo.ERROR.code);
            }
        } catch (Exception e) {
            logger.error(">>>>>>>>>>>>>修改用户ID为 ： " + jsonObject.getLong("userId") + "密码信息失败", e);
            flag = 3;
            objectMap.put("status", flag);
            return returnJson(objectMap, ERROR, ErpInfo.ERROR.code);
        }
    }

    /**
     * 获取全部用户数据列表
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/getAllList")
    public BaseResponseInfo getAllList(HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            List<User> dataList = userService.getUser();
            if (dataList != null) {
                data.put("userList", dataList);
            }
            res.code = 200;
            res.data = data;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "获取失败";
        }
        return res;
    }


    /**
     * create by: cjl
     * description:
     * 新增用户及机构和用户关系
     * create time: 2019/3/8 16:06
     *
     * @return java.lang.Object
     * @Param: beanJson
     */
    @PostMapping("/addUser")
    @ResponseBody
    public Object addUser(@RequestBody JSONObject obj, HttpServletRequest request) throws Exception {


        JSONObject result = ExceptionConstants.standardSuccess();
        Long userNumLimit = Long.parseLong(redisService.getObjectFromSessionByKey(request, "userNumLimit").toString());
        Long count = userService.countUser(null, null);
        if (count >= userNumLimit) {
            throw new BusinessParamCheckingException(ExceptionConstants.USER_OVER_LIMIT_FAILED_CODE,
                    ExceptionConstants.USER_OVER_LIMIT_FAILED_MSG);
        } else {
            UserEx ue = JSONObject.parseObject(obj.toJSONString(), UserEx.class);
            userService.addUserAndOrgUserRel(ue);


            SysUser user = new SysUser();
            user.setPassword(ue.getPassword());
            user.setUsername(ue.getUsername());
            user.setRealname(ue.getUsername());
            user.setCreateTime(new Date());//设置创建时间

            String salt = oConvertUtils.randomGen(8);
            user.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            user.setPassword(passwordEncode);
            user.setStatus(1);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            SysUser byId = sysUserService.getById(((LoginUser) SecurityUtils.getSubject().getPrincipal()).getId());
            user.setCreateBy(byId.getUsername());
            sysUserService.addUserWithRole(user, "1382502476621725697");
            // sysUserService.addUserWithDepart(user, selectedDeparts);


        }
        return result;
    }

    /**
     * create by: cjl
     * description:
     * 修改用户及机构和用户关系
     * create time: 2019/3/8 16:06
     *
     * @return java.lang.Object
     * @Param: beanJson
     */
    @PutMapping("/updateUser")
    @ResponseBody
    public Object updateUser(@RequestBody JSONObject obj) throws Exception {
        JSONObject result = ExceptionConstants.standardSuccess();
        UserEx ue = JSONObject.parseObject(obj.toJSONString(), UserEx.class);
        userService.updateUserAndOrgUserRel(ue);
        return result;
    }

    /**
     * 注册用户
     *2022.1.17 更改  不允许新用户注册
     * @param ue
     * @return
     * @throws Exception
     */
//    @PostMapping(value = "/registerUser")
    public Object registerUser(@RequestBody UserEx ue,
                               HttpServletRequest request) throws Exception {
        JSONObject result = ExceptionConstants.standardSuccess();
        ue.setUsername(ue.getLoginName());
        userService.checkUserNameAndLoginName(ue); //检查用户名和登录名
        ue = userService.registerUser(ue, manageRoleId, request);
        return result;
    }

    @RequestMapping("/getOrganizationUserTree")
    public JSONArray getOrganizationUserTree() throws Exception {
        JSONArray arr = new JSONArray();
        List<TreeNodeEx> organizationUserTree = userService.getOrganizationUserTree();
        if (organizationUserTree != null && organizationUserTree.size() > 0) {
            for (TreeNodeEx node : organizationUserTree) {
                String str = JSON.toJSONString(node);
                JSONObject obj = JSON.parseObject(str);
                arr.add(obj);
            }
        }
        return arr;
    }

    /**
     * 获取当前用户的角色类型
     *
     * @param request
     * @return
     */
    @GetMapping("/getRoleTypeByCurrentUser")
    public BaseResponseInfo getRoleTypeByCurrentUser(HttpServletRequest request) {
        BaseResponseInfo res = new BaseResponseInfo();
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            String roleType = redisService.getObjectFromSessionByKey(request, "roleType").toString();
            data.put("roleType", roleType);
            res.code = 200;
            res.data = data;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "获取失败";
        }
        return res;
    }

    @GetMapping(value = "/randomImage/{key}")
    public BaseResponseInfo randomImage(HttpServletResponse response, @PathVariable String key) {
        BaseResponseInfo res = new BaseResponseInfo();
        try {
            Map<String, Object> data = new HashMap<>();
            String codeNum = Tools.getCharAndNum(4);
            String base64 = RandImageUtil.generate(codeNum);
            data.put("codeNum", codeNum);
            data.put("base64", base64);
            res.code = 200;
            res.data = data;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "获取失败";
        }
        return res;
    }

    /**
     * 批量设置状态-启用或者禁用
     *
     * @param jsonObject
     * @param request
     * @return
     */
    @PostMapping(value = "/batchSetStatus")
    public String batchSetStatus(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request) throws Exception {
        Byte status = jsonObject.getByte("status");
        String ids = jsonObject.getString("ids");
        Map<String, Object> objectMap = new HashMap<>();
        int res = userService.batchSetStatus(status, ids);
        if (res > 0) {
            return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
        }
    }


}
